package 递归回溯;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

public class No17电话号码的字母组合 {

    /**
     * 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。
     * 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
     *
     * 示例:
     * 输入："23"
     * 输出：["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
     */

    private String[] arr={"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    private List<String> list=new ArrayList<>();

    //每一个键位都可以递归
    public List<String> letterCombinations(String digits) {
        if(digits==null||digits.equals(""))
            return new ArrayList<>();
        dg2(digits,new StringBuilder(),0);
        return list;
    }

    private void dg2(String digits,StringBuilder sb,int index){
        /**
         * (1)ad,ae,af,bd,be,bf,cd,ce,cf
         * 每一位递归完后面的每一位
         */
        if(index==digits.length()) {
            System.out.println("终点,加入:"+sb.toString());
            list.add(sb.toString());
            return;
        }

        char c = digits.charAt(index);
        String letters=arr[c-'0'];

        for (int i = 0; i < letters.length(); i++) {
            char str = letters.charAt(i);
            System.out.println("新增成员:"+str);
            sb.append(str);
            dg2(digits,sb,index+1);
            System.out.println("成员退休:"+str);
            sb.delete(sb.length()-1,sb.length());
        }
    }

    private void dg(String digits,StringBuilder sb,int index){
        if(index==digits.length()){
            list.add(sb.toString());
            return;
        }
        String numberS=arr[digits.charAt(index)-'0'];//获取当前字母组
        for (int i = 0; i < numberS.length(); i++) {
            sb.append(numberS.charAt(i));
            dg(digits, sb, index + 1);
            sb.delete(sb.length() - 1, sb.length());
        }
    }

    public static void main(String[] args) {
        No17电话号码的字母组合 n=new No17电话号码的字母组合();
        List<String> list = n.letterCombinations("236");
        System.out.println(JSON.toJSONString(list));
    }

}